#include "SetOwnAvatarTask.h"
#include  <wx/wfstream.h>
#include "../../../utils/md5.h"
#include "../packages/ssi/CliSsiXAdd.h"
#include "../packages/ssi/CliSsiXUpdate.h"
#include "../packages/avatar/CliIconUpload.h"

namespace Impp
{

SetOwnAvatarTask::SetOwnAvatarTask(Oscar* oscar, dword requestId, const wxString & avatarFile) :
	Task(TASK_SET_OWN_AVATAR, oscar,TASK_HANDLE_REQUESTID,(qword)requestId,(time_t)12),avatarFile(avatarFile),reuqestSent(false)
{
	if(!oscar->serviceConnectionRequested() && !oscar->getServiceConnection()->isConnected()){
		oscar->requestServiceConnection();
	}else{
		if(oscar->getServiceConnection()->isConnected()){
			sendRequest();
		}
	}
}

SetOwnAvatarTask::~SetOwnAvatarTask()
{
}

void SetOwnAvatarTask::timedOut(){
	wxLogDebug(wxT("SetOwnAvatarTask::timedOut: task timed out"));
}

void SetOwnAvatarTask::sendRequest(){
	
	wxFileInputStream inputFileForHash(avatarFile);


	
	wxMemoryBuffer buf(inputFileForHash.GetSize());
	inputFileForHash.Read(buf.GetData(),buf.GetBufSize());
	
	wxASSERT(inputFileForHash.LastRead() == inputFileForHash.GetSize());


	md5_context ctx;
	md5_starts( &ctx );
	md5_update( &ctx, (uint8 *) buf.GetData(), buf.GetBufSize());
	md5_finish( &ctx, hash );
	
	wxLogDebug(wxT("hash is: %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X %X"), hash[0],hash[1],hash[2],hash[3],hash[4],hash[5],hash[6],hash[7],hash[8],hash[9],hash[10],hash[11],hash[12],hash[13],hash[14],hash[15]);
	
	OscarServerCon* bos = oscar->getBosConnection();
	dword requestId = bos->nextRequestId();
	
	SsiPool* pool = oscar->getSsi();
	
	Item* ownAvatar = pool->getItem(SSI_OWN_AVATAR);
	
	if(ownAvatar == NULL){
		bos->sendPackage(DATA, new CliSsiXAdd(requestId,oscar,hash),PRIORITY_HIGHT);
	}else{
		bos->sendPackage(DATA, new CliSsiXUpdate(requestId,oscar,hash),PRIORITY_HIGHT);
	}
	
	handle = requestId;
	
	wxLogDebug(wxT("SetOwnAvatarTask::sendReques: ssi sent"));
	reuqestSent = true;
	

}

bool SetOwnAvatarTask::checkForTimeOut(const time_t & now){
	if(Task::checkForTimeOut(now)){
		return true;
	}
	if(!reuqestSent && oscar->getServiceConnection()->isConnected()){
		sendRequest();
	}
	return false;
}

void SetOwnAvatarTask::srvExtStatus(byte* avatarHash){
	wxLogDebug(wxT("SetOwnAvatarTask::srvExtStatus: uploading avatar"));
	OscarServerCon* service = oscar->getServiceConnection();
	dword requestId = service->nextRequestId();
	service->sendPackage(DATA,new CliIconUpload(avatarFile,requestId),PRIORITY_HIGHT);
	handle = requestId;

}

void SetOwnAvatarTask::srvIconUploadAck(byte* avatarHash){
	wxLogDebug(wxT("SetOwnAvatarTask::srvExtStatus: uploading avatar succedfull!"));
}


}
